package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Slf4j
@Service
public class ApUserLoginServiceImpl extends ServiceImpl<ApUserMapper, ApUser>implements ApUserLoginService {

    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * app登录
     * @param loginDTO
     * @return
     */
    @Override
    public ResponseResult login(LoginDTO loginDTO) {
        //todo 检查参数
        if (loginDTO.getEquipmentId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询等录用户
        if (StringUtils.isNotBlank(loginDTO.getPhone())&&StringUtils.isNotBlank(loginDTO.getPassword())){
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getStatus, false)//todo 判断用户状态是否正常 0正常-false 1锁定-true
                    .eq(ApUser::getPhone, loginDTO.getPhone()));//todo 校验用户手机号是否同
            if (apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"请检查手机号");
            }
            //数据库密码检查  .getBytes()将数据放到字节数组中
            String dbPassword = DigestUtils.md5DigestAsHex((loginDTO.getPassword() + apUser.getSalt()).getBytes());
            if (!dbPassword.equals(apUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }
            //todo 获取token
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("token",token);
            apUser.setPassword("");
            apUser.setSalt("");
            hashMap.put("user",apUser);
            return ResponseResult.okResult(hashMap);
        }else {
            if (loginDTO.getEquipmentId()==null){
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"无效设备id");
            }
            //todo 根据设备id生成token
            HashMap<String, Object> map = new HashMap<>();
            String token = AppJwtUtil.getToken(0L);
            map.put("token",token);
            return ResponseResult.okResult(map);

        }
    }
}
